package net.ufrog.common.spring.interceptor;

import net.ufrog.common.Logger;
import net.ufrog.common.app.App;
import net.ufrog.common.exception.ServiceException;
import net.ufrog.common.web.RequestFile;
import net.ufrog.common.web.RequestParam;
import net.ufrog.common.web.app.WebApp;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ultrafrog, ufrog.net@gmail.com
 * @version 0.1, 2016-08-04
 * @since 0.1
 */
public class MultipartRequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if (httpServletRequest instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) httpServletRequest;
            RequestParam requestParam = App.current(WebApp.class).getRequestParam();
            Map<String, RequestFile[]> mFiles = new HashMap<>();

            multipartHttpServletRequest.getMultiFileMap().forEach((k, v) -> {
                List<RequestFile> lRequestFile = new ArrayList<>(v.size());
                v.forEach(file -> {
                    try {
                        lRequestFile.add(new RequestFile(file.getName(), file.getOriginalFilename(), file.getSize(), file.getInputStream()));
                    } catch (IOException e) {
                        throw new ServiceException(e.getMessage(), e);
                    }
                });
                mFiles.put(k, lRequestFile.toArray(new RequestFile[] {}));
            });
            requestParam.getParams().putAll(multipartHttpServletRequest.getParameterMap());
            requestParam.getFiles().putAll(mFiles);
            Logger.debug("the request is multipart http servlet request.");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {}

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {}
}
